package com.funo.logic.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONObject;
import com.funo.logic.response.HandleResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * 服务编排控制器
 * @since 2024年7月17日19:11:24
 * @author cms
 */
@RestController
@RequestMapping("logicArrange")
public class LogicArrangeController extends AbstractController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 保存或者更新
     * @param data
     * @return HandleResult
     * @since 2024年7月17日19:11:24
     * @author cms
     */
    @PostMapping("saveOrUpdate")
    public HandleResult saveOrUpdate(@RequestBody JSONObject jsonObject, @RequestParam(required = false) String id) {
        if (StringUtils.isNotEmpty(id)) {
            stringRedisTemplate.delete(getCacheKey(id));
        } else {
            id = UUID.fastUUID().toString();
        }
        stringRedisTemplate.opsForValue().set(getCacheKey(id), jsonObject.toString());
        return HandleResult.success(id);
    }

    @GetMapping("getById")
    public HandleResult getById(@RequestParam String id) {
        if (stringRedisTemplate.hasKey(getCacheKey(id))) {
            return HandleResult.success(stringRedisTemplate.opsForValue().get(getCacheKey(id)));
        }
        return HandleResult.success();
    }

    @Override
    public String getCachePrefix() {
        return "logicArrange:";
    }
}
